﻿using System;
using System.Windows;
using System.Windows.Threading;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDO.Utilities
{
    public class ErrorNotifyEventArgs : EventArgs
    {
        public int ErrorId { get; set; }
        public string Message { get; set; }
        public string StackTrace { get; set; }
        public string Description { get; set; }
        public int Severity { get; set; }

        public override string ToString()
        {
            return "Error ID:" + ErrorId + ", Severity: " + Severity + Environment.NewLine + Message + Environment.NewLine + "Stack Trace:";
        }
    }


    public class ErrorDispatcher
    {
        private static ErrorDispatcher _instance;
        private Dispatcher _dispatcher;

        public Dispatcher Dispatcher
        {
            get { return _dispatcher; }
            set { _dispatcher = value; }
        }

        public static ErrorDispatcher Instance
        {
            get
            {
                if (null == _instance)
                {
                    _instance = new ErrorDispatcher();
                }
                return _instance;
            }
        }

        private event EventHandler<ErrorNotifyEventArgs> _errorEventHandler;

        public event EventHandler<ErrorNotifyEventArgs> OnError
        {
            add
            {
                _errorEventHandler += value;
            }
            remove { _errorEventHandler -= value; }
        }

        public void NotifyError(ErrorNotifyEventArgs e)
        {
            //if (_errorEventHandler == null || _dispatcher == null)
            //{
            //    // Normally, the _errorEventHandler would log and display errors, 
            //    // but since there is none defined, log it here.
            //    LogEntry log = new LogEntry() { Message = e.Message, StackTraceData = e.StackTrace };
            //    log.Title = "NotifyError called with no defined event handler.";
            //    Logger.WriteError(log);

            //    // Since we don't have a dispatcher or an eventhandler, just display a messagebox.
            //    System.Windows.MessageBox.Show(e.ToString(), "Generic Error");
            //}
            //else
            {
                if (_dispatcher.CheckAccess())
                {
                    _errorEventHandler(this, e);
                }
                else
                {
                    _dispatcher.BeginInvoke(DispatcherPriority.Background, (SendOrPostCallback)delegate { _errorEventHandler(this, e); }, null);
                }
            }
        }

    }
}
